package logic

/*
import (
	"context"
	"encoding/json"
	"errors"
	"github.com/chromedp/cdproto/page"
	"github.com/chromedp/chromedp"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"regexp"
	"time"
)

//模拟浏览器栗子
func chromedpGetDouYin() {
	rand.Seed(time.Now().UnixNano())
	//var videoUrl = "https://v26-web.douyinvod.com/fa5dd5c379f28fa0f1b91851b0e81d25/62a41b10/video/tos/cn/tos-cn-ve-15c001-alinc2/42724b9491334209b42291ba8319ecca/?a=6383&ch=26&cr=0&dr=0&lr=all&cd=0%7C0%7C0%7C0&cv=1&br=358&bt=358&cs=0&ds=6&ft=OyFYlOZZI0PD12faRud3wUzdOrSHlg9N1O-&mime_type=video_mp4&qs=4&rc=Njk1OWZnNDU5NGU3Zjk5aEBpMzppdDo6ZmxpZDMzNGkzM0BeMjUtYTAzXzExLTM1YTUyYSMwZWZhcjRnbjBgLS1kLTBzcw%3D%3D&l=021654918295472fdbddc0300fff0010a8ec31800000033cc6e4d"
	//_ = DownloadFile("1.mp4", videoUrl)
	gin.SetMode(gin.DebugMode)
	router := gin.Default()

	router.LoadHTMLGlob("templates/*")
	//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
	router.Static("/video", "video")
	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "抖音视频解析",
		})
	})

	router.POST("/parse", func(c *gin.Context) {
		//c.JSON(200, gin.H{
		//	"code": "200",
		//	"msg":  "解析成功",
		//	"url":  "/video/7f32d2b4-9a62-453c-a575-cdf5ad3e1f3d.mp4",
		//})
		//获取视频
		var txt = c.PostForm("txt")
		var uri = parseURI(txt)
		if uri == "" {
			c.JSON(200, gin.H{
				"code": "500",
				"msg":  "解析失败",
			})
			return
		}

		//此处链接解析成功
		videoUrl, err := getVideoUri(uri)
		if err != nil {
			c.JSON(200, gin.H{
				"code": "500",
				"msg":  "解析失败",
			})
			return
		}
		//下载视频
		filename := "video/" + uuid.NewV4().String() + ".mp4"
		err = DownloadFile2(filename, "https:"+videoUrl)
		if err != nil {
			c.JSON(200, gin.H{
				"code": "500",
				"msg":  "下载视频失败",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": "200",
			"msg":  "解析成功",
			"url":  "/" + filename,
		})
	})
	_ = router.Run(":8080")
}

//解析链接
func parseURI(str string) string {
	reg := regexp.MustCompile(`.*?(https://.*?) .*?`)
	info := reg.FindAllStringSubmatch(str, -1)
	if len(info) <= 0 {
		return ""
	}
	return info[0][1]
}

// DownloadFile2 下载文件
func DownloadFile2(fileName string, url string) error {
	req, err := http.NewRequest("GET", url, nil)
	req.Header.Set("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Mobile Safari/537.36")

	out, err := os.Create(fileName + ".tmp")
	if err != nil {
		return err
	}

	resp, err := (&http.Client{}).Do(req)
	if err != nil {
		out.Close()
		return err
	}
	defer resp.Body.Close()

	if _, err = io.Copy(out, resp.Body); err != nil {
		out.Close()
		return err
	}

	out.Close()
	if err = os.Rename(fileName+".tmp", fileName); err != nil {
		return err
	}
	return nil
}

// getVideoUri 获取视频地址 "https://v.douyin.com/Y8pKGB4/"
func getVideoUri(uri string) (string, error) {
	//content, err := ioutil.ReadFile("1.txt")
	//if err != nil {
	//	panic(err)
	//}
	//
	//result := string(content)
	//reg := regexp.MustCompile(`<script id="RENDER_DATA" type="application/json">(.*?)</script>`)
	//info := reg.FindAllStringSubmatch(result, -1)
	//if len(info) <= 0 || len(info[0]) <= 0 {
	//	panic("未匹配到")
	//}
	//
	//str, _ := url.QueryUnescape(info[0][1])
	//var mp = make(map[string]interface{})
	//err = json.Unmarshal([]byte(str), &mp)
	//if err != nil {
	//	panic(err)
	//}
	//var out []string
	//parseVideoUrls(mp, &out)
	//
	//log.Println(out[0])
	options := []chromedp.ExecAllocatorOption{
		chromedp.Flag("headless", true), // debug使用
		chromedp.Flag("blink-settings", "imagesEnabled=false"),
		chromedp.UserAgent(`Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36`),
	}

	options = append(chromedp.DefaultExecAllocatorOptions[:], options...)
	ctx, cancel := chromedp.NewExecAllocator(context.Background(), options...)
	defer cancel()

	ctx, cancel = chromedp.NewContext(ctx)
	defer cancel()
	//超时时间
	ctx, cancel = context.WithTimeout(ctx, 30*time.Second)
	defer cancel()

	//载入js文件
	js, _ := ioutil.ReadFile("stealth.min.js")

	var result string
	_ = chromedp.Run(ctx, chromedp.Tasks{
		chromedp.ActionFunc(func(ctx context.Context) error {
			javascript := string(js)
			_, _ = page.AddScriptToEvaluateOnNewDocument(javascript).Do(ctx)

			return nil
		}),
		chromedp.Navigate(uri),
		//chromedp.WaitVisible(`#RENDER_DATA`),
		chromedp.OuterHTML("#RENDER_DATA", &result),
	})

	//fmt.Println(result)
	//_ = ioutil.WriteFile("1.txt", []byte(result), 0755)

	reg := regexp.MustCompile(`<script id="RENDER_DATA" type="application/json">(.*?)</script>`)
	info := reg.FindAllStringSubmatch(result, -1)
	if len(info) <= 0 || len(info[0]) <= 0 {
		return "", errors.New("未匹配到")
	}

	str, _ := url.QueryUnescape(info[0][1])
	var mp = make(map[string]interface{})
	err := json.Unmarshal([]byte(str), &mp)
	if err != nil {
		return "", err
	}
	var out []string
	parseVideoUrls(mp, &out)

	return out[0], nil
}

//解析视频地址
func parseVideoUrls(mp map[string]interface{}, out *[]string) {
	var ret []string
	for k, v := range mp {
		switch value := v.(type) {
		case map[string]interface{}:
			parseVideoUrls(value, out)
		case []interface{}:
			if k == "playAddr" {
				for _, q := range value {
					ret = append(ret, q.(map[string]interface{})["src"].(string))
				}

				*out = ret
			}
		}
	}
}
*/
